<template>
    <div class="count-box">
        <button @click="handleSub" class="minus">-</button>
        <!-- 子组件通过props接收值，并且监听自定义事件 -->
        <input :value="value" @change="handleChange" type="number" class="inp">
        <button @click="handleAdd" class="add">+</button>
    </div>
</template>

<script>
export default {
  // 子组件通过props接收值，再进行内部处理
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  methods: {
    // 通过 $emit方法触发自定义事件来将新的值传递回给父组件
    // v-model 会默认传递一个input事件
    handleAdd () {
      this.$emit('input', this.value + 1)
    },
    handleSub () {
      if (this.value === 1) {
        this.$toast('宝贝数量不能再减少了~')
        return
      }
      this.$emit('input', this.value - 1)
    },
    handleChange (e) {
      const num = +e.target.value
      if (num < 0 || Number.isInteger(num) === false) {
        e.target.value = this.value
        return
      }
      this.$emit('input', num)
    }
  }

}
</script>

<style lang="less" scoped>
.count-box {
    display: flex;
    width: 110px;
    .add, .minus{
        width: 30px;
        height: 30px;
        border: none;
        outline: none;
        background-color: #efefef;
    }
    .inp{
        width: 40px;
        height: 30px;
        margin:0 5px;
        border: none;
        outline: none;
        background-color: #efefef;
        text-align: center;
    }
}
</style>
